﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Configuration;
using NetDimension.Weibo;
using LitJson;
using System.Timers;
using System.Diagnostics;
using NetDimension.Weibo.Entities.status;
using System.IO;
using System.Text;
using System.Globalization;

/// <summary>
///GrabUserCounts 的摘要说明
/// </summary>
public class GrabUserCounts
{
    private Timer timer;

    static string AppKey = "2527812079";
    static string AppSecret = "cb5db8c7c10403cf320c945949f16abc";
    static DateTime LastGrabTime = DateTime.Now.AddDays(-1);
    static DateTime NextGrabTime;
    static string ApiUrl = @"https://api.weibo.com/2/statuses/user_timeline.json";
    static CultureInfo culture = CultureInfo.CreateSpecificCulture("en-US");
    static string DateFormat = "ddd MMM dd HH:mm:ss zzz yyyy";

	public GrabUserCounts()
	{
	}

    public void Start()
    {
        NextGrabTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 23, 30, 59);

        if (NextGrabTime < DateTime.Now)//如果服务启动时，已经超过抓取数据的时间，就立即启动
        {
            LastGrabTime = NextGrabTime.AddDays(-1);
            timer_Elapsed(null, null);
        }
        else
        {
            timer = new Timer((NextGrabTime.Ticks - DateTime.Now.Ticks)/10000);
            timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
            timer.Start();
        }
    }

    public void Stop()
    {
        if (timer != null)
            timer.Stop();
    }

    protected void timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        if(timer != null)
            timer.Elapsed -= timer_Elapsed;

        GrabUserData();

        //删除7天前的数据
        new DBAccountStatistics().DeleteBefore(DateTime.Now.AddDays(-7));


        LastGrabTime = DateTime.Now;
        NextGrabTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 23, 30, 59);

        timer = new Timer((NextGrabTime.Ticks - DateTime.Now.Ticks)/10000);
        timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
        timer.Start();
    }
    private void GrabUserData()
    {
        OAuth  oauth = null;
        Client Sina = null;
            
        List<BlogAccountData> accountList = new DBBlogAccount().SelectList();
        foreach (BlogAccountData account in accountList)
        {
            oauth = new OAuth(AppKey, AppSecret, account.accessToken, "");
            TokenResult result = oauth.VerifierAccessToken();	//测试保存的AccessToken的有效性
            if (result != TokenResult.Success)  
            {
                Log.Write(account.account + " Token 验证失败 !" + result.ToString());
                continue;
            }  

            AccountStatistics accountInfo = new AccountStatistics();
            accountInfo.Date = DateTime.Now;
            accountInfo.AccountName = account.account;

            Sina = new Client(oauth);
            string UID = Sina.API.Account.GetUID();
            accountInfo.FollowersCount = Sina.API.Users.Show(UID,"").FollowersCount;
            //public string UserTimeline(string uid = "", string screenName = "", string sinceID = "", string maxID = "", int count = 50, int page = 1, bool baseApp = false, int feature = 0, bool trimUser = false)
            DateTime curGrabTime = DateTime.Now;
            int nPage = 1;

            Log.Write("Begin Grab data for account:" + accountInfo.AccountName);
            while(curGrabTime >= LastGrabTime)  
            {
                string url = ApiUrl + "?trim_user=1&access_token=" + account.accessToken + "&page=" + nPage.ToString() + "&uid=" + UID;

                Stream ReceiveStream = URLRequest.GetRequest(url);
                if (ReceiveStream != null)
                {
                    StreamReader reader = new StreamReader(ReceiveStream);
                    string jsonStr = reader.ReadToEnd();
                    reader.Close();
                    ReceiveStream.Close();

                    JsonData json = JsonMapper.ToObject(jsonStr);
                    if (json != null)
                    {
                        for (int i = 0; i < json["statuses"].Count && curGrabTime >= LastGrabTime; ++i)
                        {
                            JsonData status = json["statuses"][i];

                            string dateStr = (string)status["created_at"];
                            DateTime createdDate = DateTime.ParseExact(dateStr, DateFormat, culture);
                            if (createdDate < curGrabTime)
                            {
                                curGrabTime = createdDate;
                            }

                            if (curGrabTime < LastGrabTime)//如果直接取到前天以后的，直接PASS
                            {
                                continue;
                            }
                            

                            accountInfo.StatusCount++;
                            accountInfo.CommentsCount += (int)status["comments_count"];
                            accountInfo.RepostCount += (int)status["reposts_count"];
                        }
                    }

                    nPage++;
                }
                else
                {
                    break;
                }
            }

            new DBAccountStatistics().Add(accountInfo);
            Log.Write("Grab OK! Save To DB");
        }
    }
}

